﻿// MedicalRulesEngine.Core/Services/RuleService.cs
using AutoMapper;
using MedicalRulesEngine.Core.DTOs;
using MedicalRulesEngine.Domain.Entities;
using MedicalRulesEngine.Infrastructure.Repositories;
using Microsoft.Extensions.Logging;
using RulesEngine.Models;
using System.Diagnostics;
using System.Linq.Dynamic.Core;
using System.Text.Json;

// 为 PagedResult 创建 using 别名以解决歧义
using PagedResultDto = System.Linq.Dynamic.Core.PagedResult<MedicalRulesEngine.Core.DTOs.RuleDto>;


namespace MedicalRulesEngine.Core.Services;

/// <summary>
/// 规则服务实现
/// 提供规则的业务逻辑操作
/// </summary>
public class RuleService : IRuleService
{
    private readonly IRuleRepository _ruleRepository;
    private readonly IMapper _mapper;
    private readonly ILogger<RuleService> _logger;
    private readonly RulesEngine.RulesEngine _rulesEngine;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="ruleRepository">规则仓储</param>
    /// <param name="mapper">对象映射器</param>
    /// <param name="logger">日志记录器</param>
    public RuleService(IRuleRepository ruleRepository, IMapper mapper, ILogger<RuleService> logger)
    {
        _ruleRepository = ruleRepository ?? throw new ArgumentNullException(nameof(ruleRepository));
        _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        _rulesEngine = new RulesEngine.RulesEngine();
    }

    /// <summary>
    /// 获取所有规则
    /// </summary>
    /// <returns>规则集合</returns>
    public async Task<IEnumerable<RuleDto>> GetAllRulesAsync()
    {
        try
        {
            _logger.LogInformation("开始获取所有规则");

            var rules = await _ruleRepository.GetAllAsync();
            var ruleDtos = _mapper.Map<IEnumerable<RuleDto>>(rules);

            _logger.LogInformation("成功获取 {Count} 条规则", ruleDtos.Count());
            return ruleDtos;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取所有规则时发生错误");
            throw;
        }
    }

    /// <summary>
    /// 根据ID获取规则
    /// </summary>
    /// <param name="id">规则ID</param>
    /// <returns>规则对象</returns>
    public async Task<RuleDto?> GetRuleByIdAsync(string id)
    {
        try
        {
            _logger.LogInformation("开始获取规则，ID: {RuleId}", id);

            var rule = await _ruleRepository.GetWithDetailsAsync(id);
            if (rule == null)
            {
                _logger.LogWarning("未找到规则，ID: {RuleId}", id);
                return null;
            }

            var ruleDto = _mapper.Map<RuleDto>(rule);
            _logger.LogInformation("成功获取规则: {RuleName}", rule.Name);

            return ruleDto;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取规则时发生错误，ID: {RuleId}", id);
            throw;
        }
    }

    /// <summary>
    /// 根据代码获取规则
    /// </summary>
    /// <param name="code">规则代码</param>
    /// <returns>规则对象</returns>
    public async Task<RuleDto?> GetRuleByCodeAsync(string code)
    {
        try
        {
            _logger.LogInformation("开始根据代码获取规则，Code: {RuleCode}", code);

            var rule = await _ruleRepository.GetByCodeAsync(code);
            if (rule == null)
            {
                _logger.LogWarning("未找到规则，Code: {RuleCode}", code);
                return null;
            }

            var ruleDto = _mapper.Map<RuleDto>(rule);
            _logger.LogInformation("成功获取规则: {RuleName}", rule.Name);

            return ruleDto;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "根据代码获取规则时发生错误，Code: {RuleCode}", code);
            throw;
        }
    }

    /// <summary>
    /// 根据工作流获取规则
    /// </summary>
    /// <param name="workflowName">工作流名称</param>
    /// <returns>规则集合</returns>
    public async Task<IEnumerable<RuleDto>> GetRulesByWorkflowAsync(string workflowName)
    {
        try
        {
            _logger.LogInformation("开始获取工作流规则，Workflow: {WorkflowName}", workflowName);

            var rules = await _ruleRepository.GetByWorkflowAsync(workflowName);
            var ruleDtos = _mapper.Map<IEnumerable<RuleDto>>(rules);

            _logger.LogInformation("成功获取工作流 {WorkflowName} 的 {Count} 条规则", workflowName, ruleDtos.Count());
            return ruleDtos;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取工作流规则时发生错误，Workflow: {WorkflowName}", workflowName);
            throw;
        }
    }

    /// <summary>
    /// 根据分类获取规则
    /// </summary>
    /// <param name="category">分类</param>
    /// <returns>规则集合</returns>
    public async Task<IEnumerable<RuleDto>> GetRulesByCategoryAsync(string category)
    {
        try
        {
            _logger.LogInformation("开始获取分类规则，Category: {Category}", category);

            var rules = await _ruleRepository.GetByCategoryAsync(category);
            var ruleDtos = _mapper.Map<IEnumerable<RuleDto>>(rules);

            _logger.LogInformation("成功获取分类 {Category} 的 {Count} 条规则", category, ruleDtos.Count());
            return ruleDtos;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取分类规则时发生错误，Category: {Category}", category);
            throw;
        }
    }

    /// <summary>
    /// 搜索规则
    /// </summary>
    /// <param name="searchTerm">搜索词</param>
    /// <param name="category">分类过滤</param>
    /// <param name="isEnabled">启用状态过滤</param>
    /// <returns>符合条件的规则集合</returns>
    public async Task<IEnumerable<RuleDto>> SearchRulesAsync(string? searchTerm = null,
        string? category = null, bool? isEnabled = null)
    {
        try
        {
            _logger.LogInformation("开始搜索规则，SearchTerm: {SearchTerm}, Category: {Category}, IsEnabled: {IsEnabled}",
                searchTerm, category, isEnabled);

            var rules = await _ruleRepository.SearchRulesAsync(searchTerm, category, isEnabled);
            var ruleDtos = _mapper.Map<IEnumerable<RuleDto>>(rules);

            _logger.LogInformation("搜索到 {Count} 条规则", ruleDtos.Count());
            return ruleDtos;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "搜索规则时发生错误");
            throw;
        }
    }

    /// <summary>
    /// 分页获取规则
    /// </summary>
    /// <param name="pageIndex">页索引</param>
    /// <param name="pageSize">页大小</param>
    /// <param name="searchTerm">搜索词</param>
    /// <param name="category">分类过滤</param>
    /// <param name="isEnabled">启用状态过滤</param>
    /// <returns>分页结果</returns>
    public async Task<PagedResultDto> GetRulesPagedAsync(int pageIndex, int pageSize,
        string? searchTerm = null, string? category = null, bool? isEnabled = null)
    {
        try
        {
            _logger.LogInformation("开始分页获取规则，Page: {PageIndex}, Size: {PageSize}", pageIndex, pageSize);

            var predicate = BuildSearchPredicate(searchTerm, category, isEnabled);
            
            // 这里使用的是仓储层的 PagedResult
            var pagedResult = await _ruleRepository.GetPagedAsync(pageIndex, pageSize, predicate);
            var ruleDtos = _mapper.Map<IEnumerable<RuleDto>>(pagedResult.Data);

            // 返回的是服务层的 PagedResultDto (别名)
            var result = new PagedResultDto
            {
                Queryable = ruleDtos.AsQueryable(),
                CurrentPage = pagedResult.PageIndex,
                PageSize = pagedResult.PageSize,
                RowCount = pagedResult.TotalCount
            };

            _logger.LogInformation("成功获取第 {PageIndex} 页规则，共 {TotalCount} 条", pageIndex, result.RowCount);
            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "分页获取规则时发生错误");
            throw;
        }
    }

    /// <summary>
    /// 创建规则
    /// </summary>
    /// <param name="request">创建规则请求</param>
    /// <returns>创建的规则</returns>
    public async Task<RuleDto> CreateRuleAsync(CreateRuleRequest request)
    {
        try
        {
            _logger.LogInformation("开始创建规则: {RuleName}", request.Name);

            // 验证规则代码唯一性
            var existingRule = await _ruleRepository.GetByCodeAsync(request.Code);
            if (existingRule != null)
            {
                throw new InvalidOperationException($"规则代码 '{request.Code}' 已存在");
            }

            // 创建规则实体
            var rule = new MetadataRule
            {
                Id = Guid.NewGuid().ToString(),
                Name = request.Name,
                Code = request.Code,
                Description = request.Description,
                WorkflowName = request.WorkflowName,
                Category = request.Category,
                SubCategory = request.SubCategory,
                Priority = (RulePriority)request.Priority,
                MetadataJson = request.Metadata != null ? JsonSerializer.Serialize(request.Metadata) : null,
                CreatedAt = DateTime.UtcNow,
                Status = RuleStatus.Draft
            };

            // 添加条件
            foreach (var conditionRequest in request.Conditions)
            {
                var condition = new RuleCondition
                {
                    Id = Guid.NewGuid().ToString(),
                    RuleId = rule.Id,
                    FieldPath = conditionRequest.FieldPath,
                    Operator = conditionRequest.Operator,
                    Value = conditionRequest.Value?.ToString(),
                    LogicalOperator = conditionRequest.LogicalOperator,
                    Order = conditionRequest.Order,
                    ParentConditionId = conditionRequest.ParentConditionId,
                    GroupName = conditionRequest.GroupName,
                    MetadataJson = conditionRequest.Metadata != null ? JsonSerializer.Serialize(conditionRequest.Metadata) : null
                };
                rule.Conditions.Add(condition);
            }

            // 添加动作
            foreach (var actionRequest in request.Actions)
            {
                var action = new Domain.Entities.RuleAction
                {
                    Id = Guid.NewGuid().ToString(),
                    RuleId = rule.Id,
                    Name = actionRequest.Name,
                    ActionType = actionRequest.ActionType,
                    ConfigJson = actionRequest.Config != null ? JsonSerializer.Serialize(actionRequest.Config) : null,
                    Order = actionRequest.Order,
                    IsEnabled = actionRequest.IsEnabled
                };
                rule.Actions.Add(action);
            }

            // 添加标签
            foreach (var tagRequest in request.Tags)
            {
                var tag = new RuleTag
                {
                    Id = Guid.NewGuid().ToString(),
                    RuleId = rule.Id,
                    Name = tagRequest.Name,
                    Value = tagRequest.Value,
                    Color = tagRequest.Color
                };
                rule.Tags.Add(tag);
            }

            // 保存到数据库
            var createdRule = await _ruleRepository.AddAsync(rule);
            var ruleDto = _mapper.Map<RuleDto>(createdRule);

            _logger.LogInformation("成功创建规则: {RuleName}, ID: {RuleId}", rule.Name, rule.Id);
            return ruleDto;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建规则时发生错误: {RuleName}", request.Name);
            throw;
        }
    }

    /// <summary>
    /// 更新规则
    /// </summary>
    /// <param name="id">规则ID</param>
    /// <param name="request">更新规则请求</param>
    /// <returns>更新后的规则</returns>
    public async Task<RuleDto> UpdateRuleAsync(string id, UpdateRuleRequest request)
    {
        try
        {
            _logger.LogInformation("开始更新规则，ID: {RuleId}", id);

            // 获取现有规则
            var existingRule = await _ruleRepository.GetWithDetailsAsync(id);
            if (existingRule == null)
            {
                throw new ArgumentException($"未找到ID为 {id} 的规则");
            }

            // 更新基本信息
            existingRule.Name = request.Name;
            existingRule.Description = request.Description;
            existingRule.Category = request.Category;
            existingRule.SubCategory = request.SubCategory;
            existingRule.Priority = (RulePriority)request.Priority;
            existingRule.IsEnabled = request.IsEnabled;
            existingRule.MetadataJson = request.Metadata != null ? JsonSerializer.Serialize(request.Metadata) : null;
            existingRule.UpdatedAt = DateTime.UtcNow;
            existingRule.Version += 1;

            // 清除现有的条件、动作和标签
            existingRule.Conditions.Clear();
            existingRule.Actions.Clear();
            existingRule.Tags.Clear();

            // 添加新的条件
            foreach (var conditionRequest in request.Conditions)
            {
                var condition = new RuleCondition
                {
                    Id = Guid.NewGuid().ToString(),
                    RuleId = existingRule.Id,
                    FieldPath = conditionRequest.FieldPath,
                    Operator = conditionRequest.Operator,
                    Value = conditionRequest.Value?.ToString(),
                    LogicalOperator = conditionRequest.LogicalOperator,
                    Order = conditionRequest.Order,
                    ParentConditionId = conditionRequest.ParentConditionId,
                    GroupName = conditionRequest.GroupName,
                    MetadataJson = conditionRequest.Metadata != null ? JsonSerializer.Serialize(conditionRequest.Metadata) : null
                };
                existingRule.Conditions.Add(condition);
            }

            // 添加新的动作
            foreach (var actionRequest in request.Actions)
            {
                var action = new Domain.Entities.RuleAction
                {
                    Id = Guid.NewGuid().ToString(),
                    RuleId = existingRule.Id,
                    Name = actionRequest.Name,
                    ActionType = actionRequest.ActionType,
                    ConfigJson = actionRequest.Config != null ? JsonSerializer.Serialize(actionRequest.Config) : null,
                    Order = actionRequest.Order,
                    IsEnabled = actionRequest.IsEnabled
                };
                existingRule.Actions.Add(action);
            }

            // 添加新的标签
            foreach (var tagRequest in request.Tags)
            {
                var tag = new RuleTag
                {
                    Id = Guid.NewGuid().ToString(),
                    RuleId = existingRule.Id,
                    Name = tagRequest.Name,
                    Value = tagRequest.Value,
                    Color = tagRequest.Color
                };
                existingRule.Tags.Add(tag);
            }

            // 更新到数据库
            var updatedRule = await _ruleRepository.UpdateAsync(existingRule);
            var ruleDto = _mapper.Map<RuleDto>(updatedRule);

            _logger.LogInformation("成功更新规则: {RuleName}, ID: {RuleId}", updatedRule.Name, updatedRule.Id);
            return ruleDto;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新规则时发生错误，ID: {RuleId}", id);
            throw;
        }
    }

    /// <summary>
    /// 删除规则
    /// </summary>
    /// <param name="id">规则ID</param>
    public async Task DeleteRuleAsync(string id)
    {
        try
        {
            _logger.LogInformation("开始删除规则，ID: {RuleId}", id);

            var rule = await _ruleRepository.GetByIdAsync(id);
            if (rule == null)
            {
                throw new ArgumentException($"未找到ID为 {id} 的规则");
            }

            await _ruleRepository.DeleteAsync(rule);
            _logger.LogInformation("成功删除规则: {RuleName}, ID: {RuleId}", rule.Name, rule.Id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除规则时发生错误，ID: {RuleId}", id);
            throw;
        }
    }

    /// <summary>
    /// 启用规则
    /// </summary>
    /// <param name="id">规则ID</param>
    public async Task EnableRuleAsync(string id)
    {
        try
        {
            _logger.LogInformation("开始启用规则，ID: {RuleId}", id);

            var rule = await _ruleRepository.GetByIdAsync(id);
            if (rule == null)
            {
                throw new ArgumentException($"未找到ID为 {id} 的规则");
            }

            rule.IsEnabled = true;
            rule.UpdatedAt = DateTime.UtcNow;

            await _ruleRepository.UpdateAsync(rule);
            _logger.LogInformation("成功启用规则: {RuleName}, ID: {RuleId}", rule.Name, rule.Id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "启用规则时发生错误，ID: {RuleId}", id);
            throw;
        }
    }

    /// <summary>
    /// 禁用规则
    /// </summary>
    /// <param name="id">规则ID</param>
    public async Task DisableRuleAsync(string id)
    {
        try
        {
            _logger.LogInformation("开始禁用规则，ID: {RuleId}", id);

            var rule = await _ruleRepository.GetByIdAsync(id);
            if (rule == null)
            {
                throw new ArgumentException($"未找到ID为 {id} 的规则");
            }

            rule.IsEnabled = false;
            rule.UpdatedAt = DateTime.UtcNow;

            await _ruleRepository.UpdateAsync(rule);
            _logger.LogInformation("成功禁用规则: {RuleName}, ID: {RuleId}", rule.Name, rule.Id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "禁用规则时发生错误，ID: {RuleId}", id);
            throw;
        }
    }

    /// <summary>
    /// 复制规则
    /// </summary>
    /// <param name="sourceRuleId">源规则ID</param>
    /// <param name="newName">新规则名称</param>
    /// <param name="newCode">新规则代码</param>
    /// <returns>复制后的规则</returns>
    public async Task<RuleDto> CloneRuleAsync(string sourceRuleId, string newName, string newCode)
    {
        try
        {
            _logger.LogInformation("开始复制规则，源ID: {SourceRuleId}, 新名称: {NewName}", sourceRuleId, newName);

            // 验证新规则代码唯一性
            var existingRule = await _ruleRepository.GetByCodeAsync(newCode);
            if (existingRule != null)
            {
                throw new InvalidOperationException($"规则代码 '{newCode}' 已存在");
            }

            var clonedRule = await _ruleRepository.CloneRuleAsync(sourceRuleId, newName, newCode);
            var ruleDto = _mapper.Map<RuleDto>(clonedRule);

            _logger.LogInformation("成功复制规则: {RuleName}, ID: {RuleId}", clonedRule.Name, clonedRule.Id);
            return ruleDto;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "复制规则时发生错误，源ID: {SourceRuleId}", sourceRuleId);
            throw;
        }
    }

    /// <summary>
    /// 验证规则
    /// </summary>
    /// <param name="rule">规则对象</param>
    /// <returns>验证结果</returns>
    public async Task<ValidationResult> ValidateRuleAsync(RuleDto rule)
    {
        try
        {
            _logger.LogInformation("开始验证规则: {RuleName}", rule.Name);

            var result = new ValidationResult { IsValid = true };

            // 基本信息验证
            if (string.IsNullOrWhiteSpace(rule.Name))
            {
                result.Errors.Add("规则名称不能为空");
                result.IsValid = false;
            }

            if (string.IsNullOrWhiteSpace(rule.Code))
            {
                result.Errors.Add("规则编码不能为空");
                result.IsValid = false;
            }

            if (string.IsNullOrWhiteSpace(rule.WorkflowName))
            {
                result.Errors.Add("工作流名称不能为空");
                result.IsValid = false;
            }

            if (string.IsNullOrWhiteSpace(rule.Category))
            {
                result.Errors.Add("规则分类不能为空");
                result.IsValid = false;
            }

            // 条件验证
            if (!rule.Conditions.Any())
            {
                result.Warnings.Add("规则没有定义任何条件");
            }
            else
            {
                foreach (var condition in rule.Conditions)
                {
                    if (string.IsNullOrWhiteSpace(condition.FieldPath))
                    {
                        result.Errors.Add($"条件 {condition.Order} 的字段路径不能为空");
                        result.IsValid = false;
                    }

                    if (string.IsNullOrWhiteSpace(condition.Operator))
                    {
                        result.Errors.Add($"条件 {condition.Order} 的操作符不能为空");
                        result.IsValid = false;
                    }
                }
            }

            // 动作验证
            if (!rule.Actions.Any())
            {
                result.Warnings.Add("规则没有定义任何动作");
            }
            else
            {
                foreach (var action in rule.Actions)
                {
                    if (string.IsNullOrWhiteSpace(action.Name))
                    {
                        result.Errors.Add($"动作 {action.Order} 的名称不能为空");
                        result.IsValid = false;
                    }

                    if (string.IsNullOrWhiteSpace(action.ActionType))
                    {
                        result.Errors.Add($"动作 {action.Order} 的类型不能为空");
                        result.IsValid = false;
                    }
                }
            }

            _logger.LogInformation("规则验证完成: {RuleName}, 有效: {IsValid}, 错误数: {ErrorCount}, 警告数: {WarningCount}",
                rule.Name, result.IsValid, result.Errors.Count, result.Warnings.Count);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "验证规则时发生错误: {RuleName}", rule.Name);
            throw;
        }
    }

    /// <summary>
    /// 执行规则
    /// </summary>
    /// <param name="ruleId">规则ID</param>
    /// <param name="inputData">输入数据</param>
    /// <returns>执行结果</returns>
    public async Task<RuleExecutionResult> ExecuteRuleAsync(string ruleId, object inputData)
    {
        var stopwatch = Stopwatch.StartNew();
        var result = new RuleExecutionResult
        {
            RuleId = ruleId,
            IsSuccess = false
        };

        try
        {
            _logger.LogInformation("开始执行规则，ID: {RuleId}", ruleId);

            // 获取规则
            var rule = await _ruleRepository.GetWithDetailsAsync(ruleId);
            if (rule == null)
            {
                throw new ArgumentException($"未找到ID为 {ruleId} 的规则");
            }

            result.RuleName = rule.Name;

            // 检查规则是否启用
            if (!rule.IsEnabled)
            {
                result.ErrorMessage = "规则未启用";
                return result;
            }

            // 构建RulesEngine规则
            var workflow = BuildWorkflow(rule);

            // 执行规则
            var ruleResults = await _rulesEngine.ExecuteAllRulesAsync(workflow.WorkflowName, inputData);

            // 处理执行结果
            var ruleResult = ruleResults.FirstOrDefault();
            if (ruleResult != null)
            {
                result.IsSuccess = true;
                result.Result = ruleResult.IsSuccess;

                // 执行动作
                if (ruleResult.IsSuccess)
                {
                    await ExecuteActionsAsync(rule.Actions.Where(a => a.IsEnabled), inputData, result);
                }
            }

            stopwatch.Stop();
            result.ExecutionTimeMs = stopwatch.ElapsedMilliseconds;

            // 记录执行日志
            await LogRuleExecutionAsync(rule, inputData, result);

            _logger.LogInformation("规则执行完成: {RuleName}, 结果: {Result}, 耗时: {ElapsedMs}ms",
                rule.Name, result.Result, result.ExecutionTimeMs);

            return result;
        }
        catch (Exception ex)
        {
            stopwatch.Stop();
            result.ExecutionTimeMs = stopwatch.ElapsedMilliseconds;
            result.ErrorMessage = ex.Message;

            _logger.LogError(ex, "执行规则时发生错误，ID: {RuleId}", ruleId);
            return result;
        }
    }

    /// <summary>
    /// 批量执行规则
    /// </summary>
    /// <param name="workflowName">工作流名称</param>
    /// <param name="inputData">输入数据</param>
    /// <returns>执行结果集合</returns>
    public async Task<IEnumerable<RuleExecutionResult>> ExecuteWorkflowRulesAsync(string workflowName, object inputData)
    {
        try
        {
            _logger.LogInformation("开始执行工作流规则，Workflow: {WorkflowName}", workflowName);

            // 获取工作流的所有启用规则
            var rules = await _ruleRepository.GetByWorkflowAsync(workflowName);
            var enabledRules = rules.Where(r => r.IsEnabled && r.Status == RuleStatus.Published);

            var results = new List<RuleExecutionResult>();

            // 按优先级顺序执行规则
            foreach (var rule in enabledRules.OrderBy(r => r.Priority))
            {
                var result = await ExecuteRuleAsync(rule.Id, inputData);
                results.Add(result);

                // 如果规则执行失败且是关键优先级，停止执行后续规则
                if (!result.IsSuccess && rule.Priority == RulePriority.Critical)
                {
                    _logger.LogWarning("关键规则执行失败，停止执行后续规则: {RuleName}", rule.Name);
                    break;
                }
            }

            _logger.LogInformation("工作流规则执行完成，Workflow: {WorkflowName}, 执行规则数: {RuleCount}",
                workflowName, results.Count);

            return results;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "执行工作流规则时发生错误，Workflow: {WorkflowName}", workflowName);
            throw;
        }
    }

    /// <summary>
    /// 构建搜索谓词
    /// </summary>
    /// <param name="searchTerm">搜索词</param>
    /// <param name="category">分类</param>
    /// <param name="isEnabled">启用状态</param>
    /// <returns>查询谓词</returns>
    private static System.Linq.Expressions.Expression<Func<MetadataRule, bool>>? BuildSearchPredicate(
        string? searchTerm, string? category, bool? isEnabled)
    {
        if (string.IsNullOrWhiteSpace(searchTerm) && string.IsNullOrWhiteSpace(category) && !isEnabled.HasValue)
        {
            return null;
        }

        return rule =>
            (string.IsNullOrWhiteSpace(searchTerm) ||
             rule.Name.Contains(searchTerm) ||
             rule.Code.Contains(searchTerm) ||
             (rule.Description != null && rule.Description.Contains(searchTerm))) &&
            (string.IsNullOrWhiteSpace(category) || rule.Category == category) &&
            (!isEnabled.HasValue || rule.IsEnabled == isEnabled.Value);
    }

    /// <summary>
    /// 构建RulesEngine工作流
    /// </summary>
    /// <param name="rule">规则实体</param>
    /// <returns>工作流对象</returns>
    private static Workflow BuildWorkflow(MetadataRule rule)
    {
        var workflow = new Workflow
        {
            WorkflowName = rule.WorkflowName,
            Rules = new List<Rule>
            {
                new Rule
                {
                    RuleName = rule.Name,
                    Expression = BuildRuleExpression(rule.Conditions),
                    Actions = new RuleActions
                    {
                        OnSuccess = new ActionInfo
                        {
                            Name = "OnSuccess",
                            Context = new Dictionary<string, object>
                            {
                                ["RuleId"] = rule.Id,
                                ["RuleName"] = rule.Name
                            }
                        }
                    }
                }
            }
        };

        return workflow;
    }

    /// <summary>
    /// 构建规则表达式
    /// </summary>
    /// <param name="conditions">条件集合</param>
    /// <returns>规则表达式</returns>
    private static string BuildRuleExpression(ICollection<RuleCondition> conditions)
    {
        if (!conditions.Any())
        {
            return "true";
        }

        var expressions = new List<string>();

        foreach (var condition in conditions.OrderBy(c => c.Order))
        {
            var expression = BuildConditionExpression(condition);
            if (!string.IsNullOrWhiteSpace(expression))
            {
                if (expressions.Any() && condition.LogicalOperator.ToUpper() == "OR")
                {
                    expressions.Add("OR");
                }
                else if (expressions.Any())
                {
                    expressions.Add("AND");
                }

                expressions.Add(expression);
            }
        }

        return string.Join(" ", expressions);
    }

    /// <summary>
    /// 构建条件表达式
    /// </summary>
    /// <param name="condition">条件对象</param>
    /// <returns>条件表达式</returns>
    private static string BuildConditionExpression(RuleCondition condition)
    {
        var fieldPath = condition.FieldPath;
        var operatorSymbol = GetOperatorSymbol(condition.Operator);
        var value = FormatValue(condition.Value, condition.Operator);

        return $"{fieldPath} {operatorSymbol} {value}";
    }

    /// <summary>
    /// 获取操作符符号
    /// </summary>
    /// <param name="operatorCode">操作符代码</param>
    /// <returns>操作符符号</returns>
    private static string GetOperatorSymbol(string operatorCode)
    {
        return operatorCode.ToLower() switch
        {
            "eq" or "equals" => "==",
            "ne" or "notequals" => "!=",
            "gt" or "greaterthan" => ">",
            "gte" or "greaterthanorequal" => ">=",
            "lt" or "lessthan" => "<",
            "lte" or "lessthanorequal" => "<=",
            "contains" => "Contains",
            "startswith" => "StartsWith",
            "endswith" => "EndsWith",
            "in" => "In",
            "notin" => "NotIn",
            _ => "=="
        };
    }

    /// <summary>
    /// 格式化值
    /// </summary>
    /// <param name="value">原始值</param>
    /// <param name="operatorCode">操作符代码</param>
    /// <returns>格式化后的值</returns>
    private static string FormatValue(string? value, string operatorCode)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            return "null";
        }

        // 对于字符串操作符，需要加引号
        if (operatorCode.ToLower() is "contains" or "startswith" or "endswith")
        {
            return $"\"{value}\"";
        }

        // 尝试解析为数字
        if (double.TryParse(value, out _))
        {
            return value;
        }

        // 尝试解析为布尔值
        if (bool.TryParse(value, out _))
        {
            return value.ToLower();
        }

        // 默认作为字符串处理
        return $"\"{value}\"";
    }

    /// <summary>
    /// 执行动作
    /// </summary>
    /// <param name="actions">动作集合</param>
    /// <param name="inputData">输入数据</param>
    /// <param name="result">执行结果</param>
    private async Task ExecuteActionsAsync(IEnumerable<Domain.Entities.RuleAction> actions, object inputData, RuleExecutionResult result)
    {
        foreach (var action in actions.OrderBy(a => a.Order))
        {
            var actionResult = new ActionExecutionResult
            {
                ActionName = action.Name,
                ActionType = action.ActionType,
                IsSuccess = false
            };

            try
            {
                // 根据动作类型执行相应的逻辑
                switch (action.ActionType.ToLower())
                {
                    case "log":
                        await ExecuteLogActionAsync(action, inputData);
                        actionResult.IsSuccess = true;
                        actionResult.Result = "日志记录成功";
                        break;

                    case "notification":
                        await ExecuteNotificationActionAsync(action, inputData);
                        actionResult.IsSuccess = true;
                        actionResult.Result = "通知发送成功";
                        break;

                    case "dataupdate":
                        await ExecuteDataUpdateActionAsync(action, inputData);
                        actionResult.IsSuccess = true;
                        actionResult.Result = "数据更新成功";
                        break;

                    default:
                        actionResult.ErrorMessage = $"未知的动作类型: {action.ActionType}";
                        break;
                }
            }
            catch (Exception ex)
            {
                actionResult.ErrorMessage = ex.Message;
                _logger.LogError(ex, "执行动作时发生错误: {ActionName}", action.Name);
            }

            result.ActionResults.Add(actionResult);
        }
    }

    /// <summary>
    /// 执行日志动作
    /// </summary>
    /// <param name="action">动作对象</param>
    /// <param name="inputData">输入数据</param>
    private async Task ExecuteLogActionAsync(Domain.Entities.RuleAction action, object inputData)
    {
        // 解析动作配置
        var config = string.IsNullOrWhiteSpace(action.ConfigJson)
            ? new { }
            : JsonSerializer.Deserialize<object>(action.ConfigJson);

        _logger.LogInformation("规则动作执行 - {ActionName}: {InputData}, 配置: {Config}",
            action.Name, JsonSerializer.Serialize(inputData), JsonSerializer.Serialize(config));

        await Task.CompletedTask;
    }

    /// <summary>
    /// 执行通知动作
    /// </summary>
    /// <param name="action">动作对象</param>
    /// <param name="inputData">输入数据</param>
    private async Task ExecuteNotificationActionAsync(Domain.Entities.RuleAction action, object inputData)
    {
        // 这里可以集成邮件、短信、推送等通知服务
        _logger.LogInformation("发送通知 - {ActionName}: {InputData}", action.Name, JsonSerializer.Serialize(inputData));
        await Task.CompletedTask;
    }

    /// <summary>
    /// 执行数据更新动作
    /// </summary>
    /// <param name="action">动作对象</param>
    /// <param name="inputData">输入数据</param>
    private async Task ExecuteDataUpdateActionAsync(Domain.Entities.RuleAction action, object inputData)
    {
        // 这里可以执行数据库更新、API调用等操作
        _logger.LogInformation("更新数据 - {ActionName}: {InputData}", action.Name, JsonSerializer.Serialize(inputData));
        await Task.CompletedTask;
    }

    /// <summary>
    /// 记录规则执行日志
    /// </summary>
    /// <param name="rule">规则对象</param>
    /// <param name="inputData">输入数据</param>
    /// <param name="result">执行结果</param>
    private async Task LogRuleExecutionAsync(MetadataRule rule, object inputData, RuleExecutionResult result)
    {
        try
        {
            var executionLog = new RuleExecutionLog
            {
                Id = Guid.NewGuid().ToString(),
                RuleId = rule.Id,
                ExecutedAt = DateTime.UtcNow,
                ExecutionTimeMs = result.ExecutionTimeMs,
                IsSuccess = result.IsSuccess,
                Result = JsonSerializer.Serialize(result),
                ErrorMessage = result.ErrorMessage,
                InputDataJson = JsonSerializer.Serialize(inputData),
                ContextJson = JsonSerializer.Serialize(result.Context)
            };

            // 这里可以通过专门的日志仓储来保存执行日志
            // await _executionLogRepository.AddAsync(executionLog);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "记录规则执行日志时发生错误");
        }
    }

}

